<template>
  <div class="user-container">
    <!-- 搜索区域 -->
    <div class="filter-container">
      <el-input
        v-model="listQuery.keyword"
        placeholder="用户名/姓名/邮箱"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-select v-model="listQuery.status" placeholder="状态" clearable class="filter-item" style="width: 110px">
        <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <button-box class="filter-item" type="primary" icon="el-icon-search" text="搜索" @click="handleFilter"></button-box>
      <button-box v-permission="'user:add'" class="filter-item" type="primary" icon="el-icon-plus" text="添加用户" @click="handleCreate"></button-box>
      <button-box class="filter-item" type="success" icon="el-icon-refresh" text="刷新" @click="handleRefresh"></button-box>
      <button-box v-permission="'user:export'" class="filter-item" type="info" icon="el-icon-download" text="导出" @click="handleExport"></button-box>
    </div>

    <!-- 表格区域 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="ID" align="center" width="80">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="用户名" min-width="110px">
        <template slot-scope="{row}">
          <span>{{ row.username }}</span>
        </template>
      </el-table-column>
      <el-table-column label="姓名" min-width="110px">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="邮箱" min-width="150px">
        <template slot-scope="{row}">
          <span>{{ row.email }}</span>
        </template>
      </el-table-column>
      <el-table-column label="角色" min-width="110px">
        <template slot-scope="{row}">
          <el-tag v-for="role in row.roles" :key="role" size="mini" style="margin-right: 5px">
            {{ role }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="100px" align="center">
        <template slot-scope="{row}">
          <el-tag :type="row.status === 1 ? 'success' : 'danger'">
            {{ row.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="160px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.createTime | dateFormat }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="320" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <button-box v-permission="'user:edit'" type="primary" size="mini" text="编辑" @click="handleUpdate(row)"></button-box>
          <button-box v-permission="'user:assign'" type="info" size="mini" text="角色" @click="handleAssignRoles(row)"></button-box>
          <button-box v-permission="'user:status'" v-if="row.status === 0" size="mini" type="success" text="启用" @click="handleModifyStatus(row, 1)"></button-box>
          <button-box v-permission="'user:status'" v-else size="mini" type="warning" text="禁用" @click="handleModifyStatus(row, 0)"></button-box>
          <button-box v-permission="'user:delete'" size="mini" type="danger" text="删除" confirm="确认删除该用户?" @click="handleDelete(row)"></button-box>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <div class="pagination-container">
      <el-pagination
        :current-page.sync="listQuery.page"
        :page-sizes="pageSizes"
        :page-size.sync="listQuery.limit"
        :layout="paginationLayout"
        :total="total"
        @size-change="handlePaginationChange"
        @current-change="handlePaginationChange"
      />
    </div>

    <!-- 用户表单对话框 -->
    <dialog-box
      :title="dialogTitle"
      :visible.sync="dialogFormVisible"
      width="500px"
      :close-on-click-modal="false"
      :append-to-body="true"
      @confirm="dialogStatus === 'create' ? createData() : updateData()"
      @cancel="dialogFormVisible = false"
    >
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="80px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="temp.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="temp.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="temp.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="dialogStatus === 'create'">
          <el-input v-model="temp.password" type="password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="角色" prop="roles">
          <el-select v-model="temp.roles" multiple placeholder="请选择角色">
            <el-option
              v-for="item in roleOptions"
              :key="item.id"
              :label="item.name"
              :value="item.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="temp.status" class="filter-item" placeholder="请选择状态">
            <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-form>
    </dialog-box>
    
    <!-- 角色分配对话框 -->
    <dialog-box
      title="分配角色"
      :visible.sync="roleDialogVisible"
      width="500px"
      :close-on-click-modal="false"
      :append-to-body="true"
      @confirm="saveRoleAssignment"
      @cancel="roleDialogVisible = false"
    >
      <div v-if="currentUser">
        <p class="user-info">
          <strong>用户:</strong> {{ currentUser.name }}
          <span class="username">({{ currentUser.username }})</span>
        </p>
        <div class="role-selection-wrapper">
          <h3 class="role-selection-title">选择角色</h3>
          <div class="role-options">
            <div 
              v-for="role in roleOptions" 
              :key="role.id" 
              class="role-option-item"
              :class="{ 'is-selected': selectedRoles.includes(role.id) }"
              @click="toggleRoleSelection(role.id)"
            >
              <el-checkbox 
                :value="selectedRoles.includes(role.id)"
                @click.native.stop
              ></el-checkbox>
              <div class="role-content">
                <div class="role-name">{{ role.name }}</div>
                <div class="role-description" v-if="role.description">{{ role.description }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </dialog-box>
  </div>
</template>

<script>
import { 
  getUserListApi, 
  createUserApi, 
  updateUserApi, 
  deleteUserApi, 
  updateUserStatusApi,
  exportUserDataApi
} from '@/api/user'
import { parseTime } from '@/utils/index'
import { exportTableToExcel } from '@/utils/excel'
import validate from '@/utils/validate'
import { checkPermission } from '@/utils/permission'


export default {
  name: 'UserManagement',
  data() {
    return {
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 10,
        keyword: '',
        status: undefined
      },
      statusOptions: [
        { label: '启用', value: 1 },
        { label: '禁用', value: 0 }
      ],
      roleOptions: [
        { id: 1, name: '超级管理员', code: 'admin', description: '拥有所有权限' },
        { id: 2, name: '普通管理员', code: 'manager', description: '拥有部分权限' },
        { id: 3, name: '用户管理员', code: 'user_manager', description: '只能管理用户' },
        { id: 4, name: '访客', code: 'visitor', description: '只有查看权限' }
      ],
      temp: {
        id: undefined,
        username: '',
        name: '',
        email: '',
        password: '',
        roles: [],
        status: 1
      },
      dialogFormVisible: false,
      dialogStatus: '',
      dialogTitle: '',
      rules: {
        username: [validate.required('用户名必填')],
        name: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
        email: [validate.required(), validate.email()],
        password: [validate.required(), validate.password()],
        roles: [{ required: true, message: '角色不能为空', trigger: 'change' }]
      },
      pageSizes: [10, 20, 50, 100], // 可选的每页条数
      paginationLayout: "total, sizes, prev, pager, next, jumper", // 分页布局
      paginationTimer: null, // 防抖计时器
      
      // 角色分配对话框
      roleDialogVisible: false,
      currentUser: null,
      selectedRoles: [],

      // 对话框确认按钮加载状态
      confirmLoading: false,


    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 获取角色列表
    getRoles() {
      // 角色列表已经在data中定义为静态数据
    },
    // 获取列表数据的主要方法，统一处理加载状态和错误
    getList() {
      this.listLoading = true;
      
      // 确保对话框关闭
      this.dialogFormVisible = false;
      this.roleDialogVisible = false;
      
      // 模拟异步请求 - 后端对接时替换为实际API调用
      // getUserListApi(this.listQuery).then(response => {
      //   const data = response.data
      //   this.list = data.items
      //   this.total = data.total
      //   this.listLoading = false
      // }).catch(err => {
      //   console.error('获取用户列表失败:', err)
      //   this.listLoading = false
      // })
      
      // 模拟数据（临时，后端对接后删除）
      setTimeout(() => {
        const mockData = {
          items: [
            { id: 1, username: 'admin', name: '超级管理员', email: 'admin@example.com', status: 1, roles: ['admin'], createTime: '2023-01-01' },
            { id: 2, username: 'manager', name: '普通管理员', email: 'manager@example.com', status: 1, roles: ['manager'], createTime: '2023-01-02' },
            { id: 3, username: 'user1', name: '张三', email: 'user1@example.com', status: 1, roles: ['user'], createTime: '2023-01-03' },
            { id: 4, username: 'user2', name: '李四', email: 'user2@example.com', status: 1, roles: ['user'], createTime: '2023-01-04' },
            { id: 5, username: 'user3', name: '王五', email: 'user3@example.com', status: 0, roles: ['user'], createTime: '2023-01-05' },
            { id: 6, username: 'user4', name: '赵六', email: 'user4@example.com', status: 1, roles: ['user'], createTime: '2023-01-06' },
            { id: 7, username: 'user5', name: '钱七', email: 'user5@example.com', status: 1, roles: ['user'], createTime: '2023-01-07' },
            { id: 8, username: 'user6', name: '孙八', email: 'user6@example.com', status: 0, roles: ['user'], createTime: '2023-01-08' },
            { id: 9, username: 'user7', name: '周九', email: 'user7@example.com', status: 1, roles: ['user'], createTime: '2023-01-09' },
            { id: 10, username: 'user8', name: '吴十', email: 'user8@example.com', status: 1, roles: ['user'], createTime: '2023-01-10' }
          ],
          total: 10
        }
        
        this.list = mockData.items
        this.total = mockData.total
        this.listLoading = false
      }, 500)
    },
    
    // 简化的分页处理，使用节流防止频繁调用
    handlePaginationChange: function() {
      if (this.paginationTimer) clearTimeout(this.paginationTimer);
      this.paginationTimer = setTimeout(() => {
        this.getList();
      }, 200);
    },
    
    // 处理筛选按钮点击
    handleFilter() {
      this.listQuery.page = 1; // 重置到第一页
      this.getList();
    },
    
    // 统一的刷新方法
    handleRefresh() {
      Object.assign(this.listQuery, { 
        page: 1,
        keyword: '',
        status: undefined
      });
      this.getList();
    },
    
    // 处理创建用户操作
    handleCreate() {
      // 检查添加用户权限
      checkPermission('user:add', () => {
        // 先关闭可能打开的对话框，重置数据并设置状态
        this.dialogFormVisible = false;
        this.resetTemp();
        
        // 设置状态并显示对话框
        this.dialogStatus = 'create';
        this.dialogTitle = '创建用户';
        this.confirmLoading = false;
        
        this.$nextTick(() => {
          this.dialogFormVisible = true;
          
          // 表单显示后清除校验
          setTimeout(() => {
            if (this.$refs.dataForm) {
              this.$refs.dataForm.clearValidate();
            }
          }, 100);
        });
      });
    },
    
    // 处理更新用户操作
    handleUpdate(row) {
      // 检查编辑用户权限
      checkPermission('user:edit', () => {
        // 先关闭可能打开的对话框
        this.dialogFormVisible = false;
        
        // 创建数据副本并设置状态
        const rowClone = JSON.parse(JSON.stringify(row));
        this.resetTemp();
        this.temp = Object.assign({}, rowClone);
        this.dialogStatus = 'update';
        this.dialogTitle = '编辑用户';
        this.confirmLoading = false;
        
        this.$nextTick(() => {
          this.dialogFormVisible = true;
          
          // 表单显示后清除校验
          setTimeout(() => {
            if (this.$refs.dataForm) {
              this.$refs.dataForm.clearValidate();
            }
          }, 100);
        });
      });
    },

    resetTemp() {
      this.temp = {
        id: undefined,
        username: '',
        name: '',
        email: '',
        password: '',
        roles: [],
        status: 1
      }
    },
    // 创建用户数据，统一处理API调用
    createData() {
      // 检查权限
      if (!checkPermission('user:add', null, { showMessage: false })) {
        this.$messageBox.error('您没有添加用户的权限');
        return;
      }

      // 表单验证
      this.$refs.dataForm.validate(async (valid) => {
        if (!valid) return;
        
        try {
          // 展示加载状态
          this.confirmLoading = true;
          
          // API调用 - 后端接入时启用
          // await createUserApi(this.temp);
          
          // 模拟创建（后端接入后移除）
          this.temp.id = this.list.length + 1;
          this.temp.createTime = new Date().toLocaleString();
          this.list.unshift(this.temp);
          
          // 关闭对话框并提示成功
          this.dialogFormVisible = false;
          this.$messageBox.success('创建成功!');
        } catch (error) {
          console.error('创建用户失败:', error);
          this.$messageBox.error('创建失败，请重试');
        } finally {
          this.confirmLoading = false;
        }
      });
    },
    
    // 更新用户数据，统一处理API调用
    updateData() {
      // 检查权限
      if (!checkPermission('user:edit', null, { showMessage: false })) {
        this.$messageBox.error('您没有编辑用户的权限');
        return;
      }

      // 表单验证
      this.$refs.dataForm.validate(async (valid) => {
        if (!valid) return;
        
        try {
          // 展示加载状态
          this.confirmLoading = true;
          
          // 准备更新数据
          const tempData = Object.assign({}, this.temp);
          
          // API调用 - 后端接入时启用
          // await updateUserApi(tempData);
          
          // 模拟更新（后端接入后移除）
          const index = this.list.findIndex(v => v.id === tempData.id);
          if (index !== -1) {
            this.list.splice(index, 1, tempData);
          }
          
          // 关闭对话框并提示成功
          this.dialogFormVisible = false;
          this.$messageBox.success('更新成功!');
        } catch (error) {
          console.error('更新用户失败:', error);
          this.$messageBox.error('更新失败，请重试');
        } finally {
          this.confirmLoading = false;
        }
      });
    },
    
    // 删除用户，使用Promise和async/await简化异步处理
    handleDelete(row) {
      // 检查权限
      checkPermission('user:delete', async () => {
        try {
          // 确认删除
          await this.$confirm('确认删除该用户?', '警告', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          });
          
          // API调用 - 后端接入时启用
          // await deleteUserApi(row.id);
          
          // 模拟删除（后端接入后移除）
          const index = this.list.findIndex(v => v.id === row.id);
          if (index !== -1) {
            this.list.splice(index, 1);
            this.total--;
          }
          
          this.$messageBox.success('删除成功!');
        } catch (error) {
          if (error !== 'cancel') {
            console.error('删除用户失败:', error);
            this.$messageBox.error('删除失败，请重试');
          }
        }
      });
    },
    
    // 修改用户状态，使用async/await简化异步流程
    handleModifyStatus(row, status) {
      // 检查权限
      checkPermission('user:status', async () => {
        try {
          const statusText = status === 1 ? '启用' : '禁用';
          
          // await updateUserStatusApi({ id: row.id, status });
          
          // 模拟状态更新（后端接入后移除）
          row.status = status;
          
          this.$messageBox.success(`${statusText}成功!`);
        } catch (error) {
          console.error('修改用户状态失败:', error);
          this.$messageBox.error('状态修改失败，请重试');
        }
      });
    },
    
    // 打开角色分配对话框，简化逻辑流程
    handleAssignRoles(row) {
      // 检查权限
      checkPermission('user:assign', () => {
        // 先关闭可能打开的对话框
        this.roleDialogVisible = false;
        
        // 准备数据
        this.currentUser = Object.assign({}, row);
        
        // 将角色名称映射到角色ID
        this.selectedRoles = (row.roles || []).map(roleName => {
          const roleObj = this.roleOptions.find(item => item.name === roleName);
          return roleObj ? roleObj.id : null;
        }).filter(Boolean); // 过滤掉null值
        
        // 显示对话框
        this.$nextTick(() => {
          this.roleDialogVisible = true;
        });
      });
    },
    
    // 保存角色分配，使用async/await简化异步流程
    saveRoleAssignment() {
      // 检查权限
      if (!checkPermission('user:assign', null, { showMessage: false })) {
        this.$messageBox.error('您没有分配角色的权限');
        return;
      }

      // 准备数据
      const roleNames = this.selectedRoles.map(id => {
        const role = this.roleOptions.find(r => r.id === id);
        return role ? role.name : null;
      }).filter(Boolean); // 过滤掉null值
      
      // 构造API参数
      const params = {
        userId: this.currentUser.id,
        roleIds: this.selectedRoles
      };
      
      // 状态更新和请求处理
      (async () => {
        try {
          // await assignUserRolesApi(params);
          
          // 模拟角色分配（后端接入后移除）
          const user = this.list.find(u => u.id === this.currentUser.id);
          if (user) {
            user.roles = roleNames;
          }
          
          this.roleDialogVisible = false;
          this.$messageBox.success('角色分配成功!');
        } catch (error) {
          console.error('分配角色失败:', error);
          this.$messageBox.error('角色分配失败，请重试');
        }
      })();
    },
    
    // 添加一个辅助方法用于模拟角色分配
    applyMockRoleAssignment(roleNames) {
      // 模拟保存
      const user = this.list.find(u => u.id === this.currentUser.id)
      if (user) {
        user.roles = roleNames
      }
      this.$messageBox.success('角色分配成功!')
      this.roleDialogVisible = false
    },

    handleExport() {
      // 检查导出权限
      checkPermission('user:export', () => {
        this.$messageBox.info('正在导出用户数据...')
        
        /* API调用部分 - 后端接口对接时取消注释
        exportUserDataApi(this.listQuery).then(response => {
          // 处理API导出响应
          const blob = new Blob([response.data], { type: response.headers['content-type'] })
          const link = document.createElement('a')
          link.href = window.URL.createObjectURL(blob)
          link.download = '用户数据.xlsx'
          link.click()
          window.URL.revokeObjectURL(link.href)
        }).catch(error => {
          console.error('导出用户数据失败:', error)
          this.exportDataLocally()
        })
        */
        
        // 模拟前端导出（后端接口对接后移除）
        this.exportDataLocally()
      })
    },

    // 添加一个辅助方法用于前端导出
    exportDataLocally() {
      // 前端导出
      const columns = [
        { label: 'ID', prop: 'id' },
        { label: '用户名', prop: 'username' },
        { label: '姓名', prop: 'name' },
        { label: '邮箱', prop: 'email' },
        { label: '角色', prop: 'roles' },
        { label: '状态', prop: 'status', formatter: (row) => row.status === 1 ? '启用' : '禁用' },
        { label: '创建时间', prop: 'createTime' }
      ]
      
      const exportData = this.list.map(item => {
        const newItem = { ...item }
        if (newItem.roles && Array.isArray(newItem.roles)) {
          newItem.roles = newItem.roles.join(', ')
        }
        newItem.status = newItem.status === 1 ? '启用' : '禁用'
        return newItem
      })
      
      exportTableToExcel(exportData, columns, '用户数据')
    },
    toggleRoleSelection(roleId) {
      const index = this.selectedRoles.indexOf(roleId);
      if (index > -1) {
        this.selectedRoles.splice(index, 1);
      } else {
        this.selectedRoles.push(roleId);
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.user-container {
  padding: 20px;
  
  .filter-container {
    padding-bottom: 10px;
    
    .filter-item {
      display: inline-block;
      vertical-align: middle;
      margin-bottom: 10px;
      margin-right: 10px;
    }
    

  }
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.user-info {
  margin-bottom: 20px;
  font-size: 16px;
  padding: 12px 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
  border-left: 4px solid #409EFF;
  
  .username {
    color: #909399;
    margin-left: 5px;
  }
}

.role-description {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.role-selection-wrapper {
  margin-top: 20px;
}

.role-selection-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
  color: #303133;
  position: relative;
  padding-left: 10px;
  
  &:before {
    content: '';
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
    width: 4px;
    height: 16px;
    background-color: #409EFF;
    border-radius: 2px;
  }
}

.role-options {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.role-option-item {
  display: flex;
  align-items: center;
  padding: 12px 15px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  transition: all 0.3s;
  cursor: pointer;
  
  &:hover {
    border-color: #409EFF;
    background-color: #f0f9ff;
  }
  
  &.is-selected {
    border-color: #409EFF;
    background-color: #ecf5ff;
    
    .role-name {
      color: #409EFF;
    }
  }
}

.role-content {
  display: flex;
  flex-direction: column;
  margin-left: 10px;
  flex: 1;
}

.role-name {
  font-size: 14px;
  font-weight: bold;
  color: #303133;
}

::v-deep .el-checkbox__label {
  padding-left: 0;
}

::v-deep .el-checkbox__inner {
  border-color: #dcdfe6;
}

::v-deep .el-checkbox__input.is-checked .el-checkbox__inner {
  background-color: #409EFF;
  border-color: #409EFF;
}
</style> 